package cn.stylefeng.guns.modular.recy.utils;

import org.springframework.stereotype.*;
import cn.stylefeng.guns.modular.recy.service.*;
import org.springframework.beans.factory.annotation.*;
import java.util.concurrent.atomic.*;
import com.baomidou.mybatisplus.core.conditions.query.*;
import com.baomidou.mybatisplus.core.conditions.*;
import cn.hutool.core.convert.*;
import cn.stylefeng.guns.modular.recy.entity.*;
import java.util.*;

@Component
public class UserNoCreator
{
    @Autowired
    private WechatUserService wechatUserService;
    private static final AtomicLong userNo;
    private final long BEGIN_VALUE = 100000L;
    
    public long getMaxUserNo() {
        final QueryWrapper<WechatUser> wechatUserQueryWrapper = (QueryWrapper<WechatUser>)new QueryWrapper();
        wechatUserQueryWrapper.select(new String[] { "max(user_no) as maxNo" });
        final Map<String, Object> map = (Map<String, Object>)this.wechatUserService.getMap((Wrapper)wechatUserQueryWrapper);
        if (map == null) {
            return 100000L;
        }
        final Object maxNo = map.get("maxNo");
        if (maxNo == null) {
            return 100000L;
        }
        return Convert.toLong(maxNo);
    }
    
    public final long incrementAndGet() {
        long current;
        long next;
        do {
            current = UserNoCreator.userNo.get();
            if (current < 100000L) {
                current = this.getMaxUserNo();
                UserNoCreator.userNo.set(current);
            }
            next = ((current >= Long.MAX_VALUE) ? 0L : (current + 1L));
        } while (!UserNoCreator.userNo.compareAndSet(current, next));
        return next;
    }
    
    static {
        userNo = new AtomicLong();
    }
}
